import { goTo } from '@/modules/move'
import { MineMemory } from './types'
import TransportTaskManager from '../transport'
import { OneToOneTransportData } from '../transport/types'
import PCTaskManager from '../../pc'

/**
 * miner 工作函数
 */
export const minerWork = function (room: MyRoom, miners: Creep[], mineMemory: MineMemory) {
    const creeps = miners.filter((creep) => !creep.spawning)

    creeps.forEach((creep) => {
        if (!mineMemory.containerId || !mineMemory.extractorId) return
        if (creep.memory.slack) return

        const container = Game.getObjectById(mineMemory.containerId)
        if (!container) {
            delete mineMemory.containerId
            return
        }

        if (!creep.pos.isEqualTo(container.pos)) {
            goTo(creep, container.pos, { range: 0 })
            return
        }

        // extractor 冷却时间为 5 tick
        if (Game.time % 6) return

        if (container.store.getFreeCapacity() >= 50) {
            const mineral = Game.getObjectById(mineMemory.mineralId)!
            const result = creep.harvest(mineral)

            if (result === ERR_NOT_FOUND) {
                delete mineMemory.extractorId
            } else if (result === ERR_NOT_ENOUGH_RESOURCES) {
                mineMemory.cooldown = mineral.ticksToRegeneration || 0
                creep.suicide()
            } else {
                if (Game.time % 5 === 0) {
                    PCTaskManager.autoAddTask(room, PWR_REGEN_MINERAL, mineral, 0, 10)
                }
            }
        }

        // 快满了找人来搬
        if (container.store.getUsedCapacity() >= 1200) {
            const TRANSPORT_MINERAL_TASK_NAME = '搬运元素矿'
            if (TransportTaskManager.searchTransportTaskByName(room, TRANSPORT_MINERAL_TASK_NAME).length) return

            let target: StructureStorage | StructureTerminal | null = null
            if (room.terminal && room.terminal.store.getFreeCapacity() > 30000) target = room.terminal
            else if (room.storage && room.storage.store.getFreeCapacity() > 30000) target = room.storage

            if (!target) {
                creep.memory.slack = 30
                return
            }

            const data: OneToOneTransportData = {
                sourceId: container.id,
                targetId: target.id,
                resInfo: Object.keys(container.store).reduce((info, type) => {
                    info[type as ResourceConstant] = {
                        require: 1e7,
                        has: 0,
                    }
                    return info
                }, {} as Record<ResourceConstant, { require: number; has: number }>),
            }
            TransportTaskManager.addOneToOneTransportTask(room, TRANSPORT_MINERAL_TASK_NAME, data, 7)
        }
    })
}
